package com.hippo.scr.article.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hippo.scr.article.document.Article;
import com.hippo.scr.article.mongorepository.ArticleRepository;
import com.hippo.scr.article.service.ArticleService;
import com.hippo.scr.article.value.ArticlePageValue;
import com.hippo.tech.framework.controller.BaseController;
import com.hippo.tech.framework.controller.HomeController;
import com.hippo.tech.framework.value.MessageValue;

@Controller
@RequestMapping("article")
public class ArticleController extends BaseController {
	private static Logger logger = Logger.getLogger(HomeController.class);
	@Autowired
	private ArticleRepository articleRepository;
	
	@Autowired
	private ArticleService articleService;

	@RequestMapping(value="/loadArticleCreationPage", method = RequestMethod.GET)
	public String loadArticleCreationPage() {
		logger.info("Inside loadArticleCreationPage");
		return "article/articleLayout";
	}
	
	@RequestMapping(value="/loadArticle/{id}", method = RequestMethod.GET)
	public String loadArticleCreationPage(@PathVariable(value="id") String id) {
		logger.info("Inside loadArticle");
		return "article/article";
	}
	
	@RequestMapping(value="/savePage", method = RequestMethod.POST)
	public @ResponseBody MessageValue savePage(ArticlePageValue  articlePage) {
		logger.info("Article value passed :  " + articlePage.toString());
		articlePage.setAppUser(getCurrentAppUser());
		
		Article article = convertArticlePageToArticle(articlePage);
		MessageValue message = new MessageValue();
		try {
			articleService.saveEpub(articlePage);
			message.setMessage("Article saved successfully");
		} catch (Exception e) {
			e.printStackTrace();
			message.setMessage("Problem in saving article");
			message.setDetailedMessage(e.getMessage());
		}
		//articleRepository.save(article);
	
		return message;
	}
	
	private Article convertArticlePageToArticle(ArticlePageValue articlePage) {
		Article article = new Article();
		article.setTitle(articlePage.getTitle());
		article.setUserPID(getCurrentUserPID());
		return article;
	}
	
	@RequestMapping(value="/loadArticleNewPage", method = RequestMethod.GET)
	public String loadArticleNewPage( Model model) {
		ArticlePageValue articlePage = new ArticlePageValue();
		model.addAttribute("articlePage", articlePage);
		return "article/articlePage";
	}
}
